package org.microsites.msg;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.jetty.websocket.WebSocket;
import org.microsites.domain.model.User;

public class Peer implements WebSocket {
    private Set<PeerListener> listeners = new HashSet<PeerListener>();
    private User user;
    
    public Peer(User u) {
        this.user = u;
    }
    
    public void addListener(PeerListener l) {
        if (l != null)
            listeners.add(l);
    }

    @Override
    public void onConnect(Outbound o) {
        for (PeerListener pl : listeners) {
            pl.onConnect(user, o);
        }
    }

    @Override
    public void onDisconnect() {
        for (PeerListener pl : listeners) {
            pl.onDisconnect(user);
        }
    }

    @Override
    public void onMessage(byte frame, String data) {
        List<String> list = splitMessage(data);
        for (PeerListener pl : listeners) {
            pl.onMessage(user, list);
        }
    }

    @Override
    public void onMessage(byte frame, byte[] data, int offset, int length) {
        this.onMessage(frame, new String(data, offset, length));
    }

    private List<String> splitMessage(String s) {
        StringBuilder sb = null;
        List<String> list = new ArrayList<String>();
        boolean esc = false;
        
        if (s != null) for (char c : s.toCharArray()) {
            if (!esc && c =='\\') {
                esc = true;
            } if (!esc && c <= ' ') {
                if (sb != null) {
                    list.add(sb.toString());
                    sb = null;
                }
            } else {
                esc = false;
                if (sb == null) sb = new StringBuilder();
                sb.append(c);
            }
        }
        
        return list;
    }
}
